package src.com.itheima.operator;

import com.itheima.pojo.Student;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * 学生操作类
 * 提供对 学生数据 增删改查 操作
 */
public class StudentOperator {
    private  static ArrayList<Student> list = new ArrayList<>();
    private Scanner sc =new Scanner(System.in);
    /**
     * 新增学生
     */
    public void add() {
        System.out.println("请输入添加的学号：");
        String id = sc.nextLine();
        int index = getIndex(id);
        if (index<0){
            Student student = inputStudentInfo(id);
            list.add(student);
            System.out.println("添加成功");
        }else{
            System.out.println("输入的学号已存在！！！");
        }
    }
    /**
     * 删除学生
     */
    public void delete() {
        System.out.println("请输入要删除的学号：");
        String id = sc.nextLine();
        int index = getIndex(id);
        if (index >= 0 ){
            list.remove(index);
            System.out.println("删除成功！");
        }else{
            System.out.println("输入的学号不存在！！！");
        }
    }
    /**
     * 修改学生
     */
    public void update() {
        System.out.println("请输入要修改的学号：");
        String id = sc.nextLine();
        int index = getIndex(id);
        if (index >= 0){
            Student student = inputStudentInfo(id);
            list.set(index,student);
            System.out.println("修改成功");
        }else {
            System.out.println("输入的学号不存在！！！");
        }
    }

    private int getIndex(String id) {
        if(list ==null || list.size() ==0){
            return -1;
        }
        for (int i = 0; i <list.size(); i++) {
            Student student =list.get(i);
            if (student.getId().equals(id)){
                return i;
            }
        }
        return -1;
    }

    /**
     * 查看所有学生
     */
    public void findAll() {
        if (list==null||list.size()==0){
            System.out.println("没有数据，请先添加！");
            return;
        }
        System.out.println("学生Id    姓名    年龄    生日");
        list.forEach(student -> System.out.println(student.getId()+"\t"+student.getName()+"\t"+student.getAge()+"\t"+student.getBirthday()));
    }
    private Student inputStudentInfo(String id) {
        System.out.println("请输入姓名：");
        String name = sc.nextLine();
        System.out.println("请输入年龄：");
        String ageStr = sc.nextLine();
        Integer age = Integer.parseInt(ageStr);
        System.out.println("请输入生日：（格式为yyyy-MM-dd）");
        String birthdayStr = sc.nextLine();
        LocalDate birthday = LocalDate.parse(birthdayStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Student student = new Student(id, name, age, birthday);
        return student;
    }
}
